<?php
/**
 * 
 * 抽象Controller,所有控制器的基类
 * 
 * @author Leo Ning <leo.ning@like18.com>
 * @version 1.0
 * @since 1.0
 * @copyright 2008-2011 LIKE18 INC.
 * @package controller
 * @abstract
 */
abstract class Action {
	protected $xajax;
	/////////////////////////
	public $referer = '';
	public $path = '';
	public $uri = '';
	public $url = '';
	public $module = '';
	
	public function __construct($here = '', $module = "") {
		global $__url, $__global;
		$this->xajax = isset ( $_SERVER ["HTTP_X_AJAX_TYPE"] ) ? $_SERVER ["HTTP_X_AJAX_TYPE"] : '';
		$this->referer = isset ( $_SERVER ['HTTP_REFERER'] ) ? $_SERVER ['HTTP_REFERER'] : '';
		$this->path = ($__global ['is_plugin_action'] ? PLUGIN_PATH : MODULE_PATH) . $module;
		$this->uri = $here;
		$this->module = $module;
		$this->url = the_safe_url ( request_uri () );
		$this->bindhooks ();
	}
	/**
	 * 加载校验规则
	 * @param string $rule 校验规则名称
	 * @return arary 校验规则集
	 */
	protected function rule($rule) {
		$frule = $this->path . DS . VALIDATE_DIR . DS . $rule . '.json';
		
		if (is_readable ( $frule )) {
			$rulec = file_get_contents ( $frule );
			$rulec = preg_replace ( '/[\\r\\n\\t]/', '', $rulec );
			if (DEBUG_DISPLAY) {
				$rules = json_decode ( $rulec, true );
			} else {
				$rules = @json_decode ( $rulec, true );
			}
			if (empty ( $rules )) {
				trigger_error ( 'no rule loaded from ' . $frule, E_USER_ERROR );
			}
			if (is_readable ( $this->path . DS . VALIDATE_DIR . DS . $rule . '.php' )) {
				include_once $this->path . DS . VALIDATE_DIR . DS . $rule . '.php';
			}
			return empty ( $rules ) ? array () : $rules;
		} else {
			trigger_error ( 'the rule file ' . $frule . ' was not found', E_USER_ERROR );
		}
		return array ();
	}
	/**
	 * 使用$rule规则对数据$data进行验证
	 * 
	 * @param string $rule 验证规则 
	 * @param array $data 要验证的数据
	 * @param boolean $strict 是否使用严格验证
	 * @return boolean|array true验证通过，反之是一个包含错误描述信息的数组
	 */
	protected function validate($rule, $data, $scope = null) {
		$rules = $this->rule ( $rule );
		$scope = is_object ( $scope ) ? $scope : $this;
		return ModelValidator::validate ( $rules, $data, true, $scope );
	}
	/**
	 * 
	 * 绑定勾子
	 */
	protected function bindhooks() {
	}
	/**
	 * base function, to be overridden
	 * @return View 要绘制的视图，如果返回值不是View的子类实例，则不启动框架的绘制器
	 */
	public abstract function execute($params);
}
?>